<template>
  <Dialog v-model="dialogVisible" :title="title">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="80px">
      <el-form-item label="用户标识">
        <el-select v-model="formData.userFlag" disabled>
          <el-option :value="0" label="系统用户" />
          <el-option :value="1" label="学员用户" />
        </el-select>
      </el-form-item>
      <el-form-item label="用户名">
        <el-input v-model="formData.userName" disabled />
      </el-form-item>
      <el-form-item label="昵称" prop="nickName">
        <el-input v-model="formData.nickName" placeholder="请输入昵称" />
      </el-form-item>
      <el-form-item label="启用" prop="enable">
        <el-switch v-model="formData.enable" :active-value="1" :inactive-value="0" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
defineOptions({ name: 'PmUserForm' })
import * as PmUserApi from '@/api/pm/user'
const message = useMessage()

const dialogVisible = ref(false)
const formLoading = ref(false)
const formRef = ref()
const mode = ref<'create' | 'update'>('create')
const title = computed(() => (mode.value === 'create' ? '新增用户' : '编辑用户'))

const formData = ref<any>({
  userId: undefined,
  userName: undefined,
  nickName: undefined,
  userFlag: 1,
  examFlag: 0,
  status:0,
  passwordText: undefined
})

const formRules = reactive({
  nickName: [{ required: true, message: '请输入昵称', trigger: 'blur' }]
})

// 打开表单
const open = (openMode: 'create' | 'update', row?: any) => {
  mode.value = openMode
  dialogVisible.value = true
  resetForm()
  if (openMode === 'update' && row) {
    formData.value = { ...row }
  }
}
defineExpose({ open })

const emit = defineEmits(['success'])

// 提交（本地模拟：返回表单数据给父组件）
const submitForm = async () => {
  const valid = await formRef.value?.validate()?.catch(() => false)
  if (!valid) return
  formLoading.value = true
  try {
    if (mode.value === 'update') {
      await PmUserApi.updateUser({
        ...formData.value,
        id: formData.value.userId,
        username: formData.value.userName,
        nickname: formData.value.nickName
      })
    }
    message.success(mode.value === 'create' ? '新增成功' : '修改成功')
    dialogVisible.value = false
    emit('success', { ...formData.value, __mode: mode.value })
  } finally {
    formLoading.value = false
  }
}

// 重置
const resetForm = () => {
  formData.value = {
    userId: undefined,
    userName: undefined,
    nickName: undefined,
    userFlag: 1,
    examFlag: false,
    passwordText: undefined
  }
  formRef.value?.resetFields?.()
}
</script>


